<template>
    <div class="dami-upload">
      <div v-for="(item,index) in fileIDList" :key="item.fileID" class="dami-upload-item">
        <img @click="del(item,index)" :id="item.imgID" :src="!item.imgSrc ? addImgIcon : translateImg(item.imgSrc,item.edit)" alt="上传文件" />
        <input v-show="(multiple == true && !item.imgSrc) || (multiple == false)" type="file" @change="fileSelect(item.fileID,item.imgID,index)" :id="item.fileID" />
      </div>
    </div>
</template>
<script>
    let addImgIcon = require('./upload.png');

    export default {
        name: 'upload',
        data () {
            return {
              addImgIcon:addImgIcon,
              fileIDList:[
                {
                  imgID:"img-"+new Date().getTime(),
                  fileID:"dami-"+new Date().getTime(),
                  edit:false,
                  imgSrc:""
                }
              ]
            };
        },
        props:['multiple','action-url','img-path'],
        methods:{
          del(item,index){
            if(item.imgSrc == ""){
              return;
            }
            this.fileIDList.splice(index,1);
          },
          translateImg(img,edit){
            console.log("llllllll:",edit)
            if(edit){
              return this.imgPath + img;
            }
            return img;
          },
          reset(){
            this.fileIDList = [
              {
                imgID:"img-"+new Date().getTime(),
                fileID:"dami-"+new Date().getTime(),
                edit:false,
                imgSrc:""
              }
            ]
          },
          initData(data){
            if(data.length == 0){
              return;
            }
            this.fileIDList = [];
            for(let i = 0; i < data.length; i++){
              if(!!data[i]){
                this.fileIDList.push({
                  imgID:"img-"+new Date().getTime() + i,
                  fileID:"dami-"+new Date().getTime() + i,
                  edit:true,
                  imgSrc:data[i]
                });
              }
            }
            if(this.multiple){
              this.fileIDList.push({
                imgID:"img-"+new Date().getTime(),
                fileID:"dami-"+new Date().getTime(),
                edit:false,
                imgSrc:""
              });
            }

          },
          upload(callback){
            window.vueInstence = this;
            
            let result = {
              res:1,
              mes:''
            };
            if(!this.actionUrl){
              result.res = 0;
              result.mes = "请配置图片上传URL";
              callback(result);
              return;
            }



            let fileList = [];
            for(let i = 0; i < this.fileIDList.length; i++){
              let fileID = this.fileIDList[i].fileID;
              if(document.getElementById(fileID).value != ""){
                fileList.push(fileID);
              }
            }
            if(fileList.length == 0){
              result.res = -1;
              result.mes = "用户没有选择图片";
              result.oldImgpath = [];
              result.imgList = [];
              for(let i = 0; i < this.fileIDList.length; i++){
                let item = this.fileIDList[i];
                if(item.edit){
                  result.oldImgpath.push(item.imgSrc);
                }
              }

              callback(result);
              return;
            }
            window.MGFile.load(this.actionUrl, fileList, result => {
              callback(result);
            });
          },
          getFileUrl(sourceId) {
            if(document.getElementById(sourceId).value == ""){
              return "";
            }
            var url;
              if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
                url = document.getElementById(sourceId).value;
              } else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
              } else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
              }
              else if(navigator.userAgent.indexOf("Safari")>0) { // Safari
                url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
              }
            return url;
          },
          fileSelect(sourceID,imgID,index){
            var url = this.getFileUrl(sourceID);
            var imgPre = document.getElementById(imgID);
            if(url == ""){
              url = addImgIcon;
            }
            imgPre.src = url;
            let _item = this.fileIDList[index];
            _item.imgSrc = url;
            _item.edit = false;
            this.fileIDList.splice(index,1,_item);
            if(this.multiple == true){
              this.fileIDList.push({
                imgID:"img-"+new Date().getTime(),
                fileID:"dami-"+new Date().getTime(),
                edit:false,
                imgSrc:""
              });
            }
          },
          initUpload(){
            (function (window) {
                var obj = {};
                obj.load = function (url, fileId, callback) {
                    var formData = new FormData();
                    if (typeof fileId == "string") {
                        var file = document.getElementById(fileId).files;
                        formData.append("fm", file[0]);
                    }
                    if (typeof fileId == "object") {
                        for (var a = 0; a < fileId.length; a++) {
                            var file = document.getElementById(fileId[a]).files;
                            formData.append(a, file[0]);
                        }
                    }
                    var ajx = new XMLHttpRequest();
                    ajx.open("post", url, true);
                    
                    ajx.onload = function () {
                        if (ajx.readyState == 4 && ajx.status == 200) {
                          let result = JSON.parse(ajx.responseText);
                          result.oldImgpath = [];
                          console.log("gggggggg:")
                          console.log(window.vueInstence.fileIDList)
                          for(let i = 0; i < window.vueInstence.fileIDList.length; i++){
                            let item = window.vueInstence.fileIDList[i];
                            if(item.edit){
                              result.oldImgpath.push(item.imgSrc);
                            }
                          }
                          callback(result);
                        } else {
                          callback({
                            res:0,
                            msg:'文件上传出错'
                          });
                        }
                    }
                    ajx.send(formData);
                }
                window.MGFile = obj;
            })(window);
          }
        },
        mounted () {
          this.initUpload();
          window.vueInstence = this;
        }
    };
</script>
<style scoped>
  .dami-upload{

  }
  .dami-upload-item{
    position: relative;
    width: 50px;
    height: 50px;
    display: inline-block;
    margin-right: 5px;
    margin-top: 5px;
  }
  .dami-upload-item img,.dami-upload-item input[type='file']{
    position: absolute;
    top:0;
    left:0;
    width: 100%;
    height: 100%;
  }
  .dami-upload-item img{
    z-index: 0;
    top:50%;
    transform: translateY(-50%);
    height: auto;
  }
  .dami-upload-item input[type='file']{
    opacity: 0;
    z-index: 1;
  }
</style>
